package org.glut.backend.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.glut.backend.domain.Orders;
import org.glut.backend.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Redis key过期事件监听器
 * 监听订单倒计时key过期，自动取消超时未支付的订单
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private IOrdersService ordersService;

    // 订单倒计时key前缀
    private static final String ORDER_COUNTDOWN_PREFIX = "order:countdown:";

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 监听Redis key过期事件
     * @param message 过期的key信息
     * @param pattern 匹配模式
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            // 获取过期的key
            String expiredKey = message.toString();
            log.info("Redis key过期: {}", expiredKey);

            // 检查是否是订单倒计时key
            if (expiredKey.startsWith(ORDER_COUNTDOWN_PREFIX)) {
                // 提取订单ID
                String orderIdStr = expiredKey.substring(ORDER_COUNTDOWN_PREFIX.length());
                Integer orderId = Integer.valueOf(orderIdStr);
                
                log.info("订单{}倒计时已过期，开始处理", orderId);
                
                // 查询订单
                Orders order = ordersService.getById(orderId);
                if (order != null && order.getStatus() == 0) {
                    order.setStatus(2); // 设置为取消状态
                    boolean updateResult = ordersService.updateById(order);
                    
                    if (updateResult) {
                        log.info("订单{}已自动取消（超时未支付）", orderId);
                    } else {
                        log.error("订单{}取消失败", orderId);
                    }
                } else if (order == null) {
                    log.warn("订单{}不存在，可能已被删除", orderId);
                } else {
                    log.info("订单{}当前状态为{}，无需取消", orderId, order.getStatus());
                }
            }
        } catch (Exception e) {
            log.error("处理Redis key过期事件时发生错误：", e);
        }
    }
}